"""Flask application factory."""
import sys
import os
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flask_restx import Api
from flask_cors import CORS

# Add parent directory to path to import config
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import config

# Initialize extensions
db = SQLAlchemy()
jwt = JWTManager()


def create_app(config_name='default'):
    """Create and configure the Flask application.
    
    Args:
        config_name: Configuration name ('development', 'production', or 'default')
        
    Returns:
        Configured Flask application instance
    """
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    
    # Set up logging first
    from app.utils.logging_config import setup_logging
    setup_logging(app)
    
    # Set up Sentry error tracking (production only)
    if not app.config.get('DEBUG', False):
        from app.utils.sentry_config import setup_sentry
        setup_sentry(app)
    
    # Set up Prometheus metrics
    from app.utils.metrics import setup_metrics
    setup_metrics(app)
    
    # Initialize extensions
    db.init_app(app)
    jwt.init_app(app)
    CORS(app, resources={
        r"/api/*": {
            "origins": ["http://localhost:8000", "http://127.0.0.1:8000"],
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization"]
        }
    })
    
    # Set up rate limiting (production only)
    if app.config.get('RATELIMIT_ENABLED', False):
        from flask_limiter import Limiter
        from flask_limiter.util import get_remote_address
        
        limiter = Limiter(
            app=app,
            key_func=get_remote_address,
            default_limits=[app.config.get('RATELIMIT_DEFAULT', '60 per minute')],
            storage_uri=app.config.get('RATELIMIT_STORAGE_URL')
        )
        app.logger.info("Rate limiting enabled")
    
    # Initialize API with Flask-RESTX
    api = Api(
        app,
        version='1.0',
        title='步语 API',
        description='步语散步应用后端API',
        doc='/api/docs'
    )
    
    # Register blueprints/namespaces
    from app.routes import register_routes
    register_routes(api)
    
    # Health check endpoint
    @app.route('/health')
    def health_check():
        """Health check endpoint for monitoring."""
        return jsonify({
            'status': 'healthy',
            'service': 'buyu-backend',
            'version': '1.0.0'
        }), 200
    
    # Create database tables
    with app.app_context():
        db.create_all()
    
    app.logger.info("Application initialization complete")
    
    return app
